package com.springboot.blog.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot.blog.entity.Menu;
import com.springboot.blog.entity.Role;
import com.springboot.blog.entity.User;
import com.springboot.blog.entity.UserRole;
import com.springboot.blog.service.IMenuService;
import com.springboot.blog.service.IRoleService;
import com.springboot.blog.service.IUserRoleService;
import com.springboot.blog.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.*;

@Controller
class AdminIndexController
{
    @Autowired
    IUserService userService;
    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IMenuService menuService;
    String PATH = "admin/index/";

    @GetMapping(value = {"/admin/index/index","/admin/index","admin"})
    public String index(Model model) {
        //获取当前用户的所有菜单
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        List<UserRole> userRoles = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        List<Integer> roleIds=new ArrayList<>();
        for (UserRole r:userRoles){
            roleIds.add(r.getRoleId());
        }
        List<Role> roles = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getId, roleIds));
        List<String> menuIds=new ArrayList<>();
        for(Role r:roles){
            String rules = r.getRules();
            String[] split = rules.split(",");
            menuIds.addAll(Arrays.asList(split));
        }

        HashSet<String> h = new HashSet<>(menuIds);
        menuIds.clear();
        menuIds.addAll(h);
        List<Map<String, Object>> maps = menuService.listMaps(new LambdaQueryWrapper<Menu>().in(Menu::getId, menuIds).eq(Menu::getType, 1).orderByAsc(Menu::getSorts));
        List<Map<String, Object>> tree = new ArrayList<>();
        buildTreeData(maps, tree, 0);
        model.addAttribute("menus",tree);
        return PATH+"index";
    }

    private void buildTreeData(List<Map<String, Object>> list, List<Map<String, Object>> tree, long parentId) {
        for (Map<String, Object> row : list) {
            if ((long) row.get("pid") == parentId) {
                List<Map<String, Object>> children = new ArrayList<>();
                buildTreeData(list, children, (long) row.get("id"));
                row.put("children", children);
                tree.add(row);
            }
        }
    }

    @RequiresPermissions("index:welcome")
    @GetMapping("/admin/index/welcome")
    public String welcome(Model model) {
        return PATH+"welcome";
    }
}
